﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using OA.BLL;

using OA.Model;
using OA.Web.Areas.Member.Controllers;
using OA.Web.Attribute;
using OA.Web.Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using X.PagedList;

namespace OA.Web.Areas.Management.Controllers
{
    [Area("Management")]
    public class NoticesController : BaseMemberController
    {

        private IMemoryCache _cache;
        public NoticesController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
        }

        [MyActionFilter("206004", "公告管理","管理中心",true, "icongonggao1")]
        public IActionResult Index(string keyword, int page = 1, int limit = 15)
        {
            return View();
        }

        [MyActionFilter("206004", "公告管理", "管理中心", true, "icongonggao1")]
        public IActionResult GetData(string keyword, int page = 1, int limit = 15)
        {
            ViewBag.Keyword = keyword;
            Expression<Func<Notice, bool>> where = m => m.Type == "公司公告";
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                where = m => m.Type == "公司公告" && (m.Title.Contains(keyword));
            }
            var list = this.dbContextFactory.DbContext.Notice.Where(where).Select(SimpleNotice.Map).OrderByDescending(m => m.ID).ToPagedList(page, limit);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.TotalItemCount,
                data = list
            };
            return Json(result);
        }


        [HttpGet]
        [MyActionFilter("206004001", "添加公告", "公告管理", false, "")]
        public IActionResult Create()
        {
            return View(new Notice() { SendTime = DateTime.Now });
        }


        [HttpPost]
        [MyActionFilter("206004001", "添加公告", "公告管理", false, "")]
        public IActionResult Create(Notice model)
        {
            BaseResult baseResult = new BaseResult();
            model.Type = "公司公告";
            if (!ModelState.IsValid)
            {
                baseResult.State = 400;
                baseResult.Msg = this.GetModelStateError(ModelState);
                return Json(baseResult);
            }
            else
            {
                this.AddInfo<Notice>(model);
                baseResult.Msg = "公告添加成功";
                return Json(baseResult);
                

            }

        }

        [HttpGet]
        [MyActionFilter("206004002", "修改公告", "公告管理", false, "")]
        public IActionResult Edit(int id)
        {
            Notice infoNotice = this.GetInfo<Notice>(id);
            if (infoNotice == null||infoNotice.Type!= "公司公告")
            {
                return Redirect("/Admin/Home/Info?msg=" + System.Web.HttpUtility.UrlEncode("沒有找到该公告", Encoding.UTF8));
            }
            return View(infoNotice);
        }

        [HttpPost]
        [MyActionFilter("206004002", "修改公告", "公告管理", false, "")]
        public IActionResult Edit(int id, Notice model)
        {
            model.Type = "公司公告";
            BaseResult baseResult = new BaseResult();
            if (!ModelState.IsValid)
            {
                baseResult.State = 400;
                baseResult.Msg = this.GetModelStateError(ModelState);
                return Json(baseResult);
            }
            Notice infoNotice = this.GetInfo<Notice>(id);
            if (infoNotice == null || infoNotice.Type != "公司公告")
            {                 
                baseResult.State = 400;
                baseResult.Msg = "沒有找到该公告";
                return Json(baseResult);
            }
            this.Update<Notice>(infoNotice, model, null, new string[] { "ID" });
            baseResult.Msg = "公告修改成功";
            return Json(baseResult);

        }



        [HttpGet]
        [MyActionFilter("206004003", "删除公告", "公告管理", false, "")]
        public IActionResult Delete(int id)
        {
            Expression<Func<Notice, bool>> where = m => m.ID == id;
            this.Delete<Notice>(where);
            return Json(new { State = 200, Msg = "公告删除成功" });
        }

        [HttpGet]
        [MyActionFilter("206004004", "指定阅读成员", "公告管理", false, "")]
        public IActionResult SetEmployees(int id)
        {
            Notice infoNotice = this.GetInfo<Notice>(id);
            ViewBag.Notice = infoNotice;

            return View();
        }

        [HttpPost]
        [MyActionFilter("206004004", "指定阅读成员", "公告管理", false, "")]
        public IActionResult SetEmployees(int id, List<string> employees)
        {
            BaseResult baseResult = new BaseResult();

            var currentList = this.dbContextFactory.DbContext.EmployeeNotice.Where(m => m.NoticeID == id).Select(m => m.EmpID).ToList();
            employees = employees.Where(m => !string.IsNullOrWhiteSpace(m)).ToList();
            var deletes = currentList.Where(m => !employees.Contains(m)).ToList();

            var addList = employees.Where(m => !currentList.Contains(m)).ToList();

            Notice infoNotice = this.GetInfo<Notice>(id);
            ViewBag.Notice = infoNotice;
            List<EmployeeNotice> items = new List<EmployeeNotice>();
            foreach (string employee in addList)
            {
                EmployeeNotice item = new EmployeeNotice();
                item.CreateDateTime = DateTime.Now;
                item.EmpID = employee;
                item.Status = 0;
                item.NoticeID = id;
                items.Add(item);
            }

            using (var trn = this.dbContextFactory.DbContext.Database.BeginTransaction())
            {
                try
                {
                    this.AddRange<EmployeeNotice>(items);
                    if (deletes.Count > 0)
                    {
                        Expression<Func<EmployeeNotice, bool>> where = m => m.NoticeID == id && deletes.Contains(m.EmpID);
                        this.Delete<EmployeeNotice>(where);
                    }
                    trn.Commit();
                    baseResult.Msg = "人员指定成功";
                    return Json(baseResult);

                }
                catch (Exception ex)
                {
                    trn.Rollback();
                    baseResult.State = 400;
                    baseResult.Msg = ex.ToString();
                    return Json(baseResult);
                }
            }

        }


    }
}
